package cn.com.fuhuitong.main.home.ui.activity

import android.content.Context
import android.text.Editable
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.BaseAbstractActivity
import cn.com.fuhuitong.main.cate.entity.CateChildEntity
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import kotlinx.android.synthetic.main.activity_search.*


@Route(path = ARouteConstance.ACTIVITY_URL_SEARCH)
class HomeSearchActivity : BaseAbstractActivity() {

    override val layoutResId: Int
        get() = R.layout.activity_search

    override fun initView() {

        image_search_back.setOnClickListener {
            if (KeyboardUtils.isSoftInputVisible(this)){
                KeyboardUtils.hideSoftInput(this)
            }
            this.finish()
        }

        text_search_content.setOnClickListener {
            edit_search_content.text = Editable.Factory.getInstance()
                .newEditable("")
            this.showSoftInputFromWindow(edit_search_content)
        }

        edit_search_content.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val search: String = edit_search_content.text.toString().trim()
                if (search.isNotEmpty()) {
                    val entity = CateChildEntity(
                        id = 0, name = edit_search_content.text.toString(), image = ""
                    )
                    entity.search = edit_search_content.text.toString()
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_GOODS_LIST)
                        .withSerializable(AppConstance.BUNDLE_CATE_CHILD, entity)
                        .navigation()
                }
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    override fun onResume() {
        super.onResume()
        this.showSoftInputFromWindow(edit_search_content)
    }

    private fun showSoftInputFromWindow(editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        val inputManager: InputMethodManager = editText.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.showSoftInput(editText, 0)
    }
}